//index.js
const fetchWechat = require('fetch-wechat');
import * as tf from '@tensorflow/tfjs-core';
import '@tensorflow/tfjs-backend-wasm';
import { setWasmPath } from '@tensorflow/tfjs-backend-wasm';
import * as blazeface from '../../model/blazeface.js'

const plugin = requirePlugin('tfjsPlugin');
const ENABLE_DEBUG = true;
//获取应用实例
const app = getApp()

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  onLoad: function () {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  onReady: async function() {
    const info = wx.getSystemInfoSync();
    console.log('platform: ' + info.platform);
    let iOS = info.system.startsWith('iOS')
    const query = wx.createSelectorQuery()
    query.select('#myCanvas').node().exec(async (res) => {
      const canvas = res[0].node
      // const gl = canvas.getContext('webgl')
      plugin.configPlugin({
        // polyfill fetch function
        fetchFunc: fetchWechat.fetchFunc(),
        // inject tfjs runtime
        tf,
        // provide webgl canvas
        canvas: iOS ? wx.createOffscreenCanvas() : canvas,
        backendName: 'wechat-webgl-' + Date.now()
      }, ENABLE_DEBUG);
      // if (info.platform == 'android') {
      //   setWasmPath('https://face-recognition-blazeface-1301186281.cos.ap-nanjing.myqcloud.com/tfjs-backend-wasm.wasm', true);
      //   tf.setBackend('wasm').then(() => console.log('set wasm as backend'));
      // }
      app.globalData.blazeFaceModel = await blazeface.load()
    })

    // query.select('#myCanvas2').fields({ node: true, size: true }).exec((res) => { 
    //   const canvas = res[0].node
    //   const ctx = canvas.getContext('2d')

    //   const dpr = wx.getSystemInfoSync().pixelRatio
    //   canvas.width = res[0].width * dpr
    //   canvas.height = res[0].height * dpr
    //   ctx.scale(dpr, dpr)
    //   ctx.fillRect(100, 100, 100, 100)
    //   ctx.fillRect(100 - 10, 200, 100 + 20, 100)
    // })
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  }
})
